<script setup lang="ts" name="SystemDictDataForm">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { getIntDictOptions } from '@/utils/dict'
import { DICT_TYPE } from '@/enums/dictEnums'
import { DictApi, DictTypeType, DictDataType } from '@/api/system/dict/index'
import { CommonStatusEnum } from '@/enums/commonEnums'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)

defineProps({
  dictTypeList: {
    type: Array<DictTypeType>,
    default: () => []
  }
})

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const visible = ref(false) // 弹窗的是否展示
const title = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  label: '',
  value: '',
  dict_type: '',
  color_type: '',
  css_class: '',
  sort: 0,
  status: CommonStatusEnum.ENABLE,
  remark: ''
})
const formRules = reactive({
  dict_type: [{ required: true, message: t('sys.dict.rules', 'title'), trigger: 'blur' }],
  label: [{ required: true, message: t('sys.dict.rules', 'label'), trigger: 'blur' }],
  value: [{ required: true, message: t('sys.dict.rules', 'value'), trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

// 数据标签回显样式
const colorTypeOptions = readonly([
  {
    value: 'default',
    label: t('color.type', 'default')
  },
  {
    value: 'primary',
    label: t('color.type', 'primary')
  },
  {
    value: 'success',
    label: t('color.type', 'success')
  },
  {
    value: 'info',
    label: t('color.type', 'info')
  },
  {
    value: 'warning',
    label: t('color.type', 'warning')
  },
  {
    value: 'danger',
    label: t('color.type', 'danger')
  }
])

/** 打开弹窗 */
const open = async (type: string, id?: number, dictType?: string) => {
  visible.value = true
  title.value = t('action', type)
  formType.value = type
  resetForm()
  if (dictType) {
    formData.value.dict_type = dictType
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DictApi.Data.detail(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as DictDataType
    if (formType.value === 'create') {
      await DictApi.Data.create(data)
      message.success(t('message', 'createSuccess'))
    } else {
      await DictApi.Data.update(data)
      message.success(t('message', 'updateSuccess'))
    }
    visible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    label: '',
    value: '',
    dict_type: '',
    color_type: '',
    css_class: '',
    status: CommonStatusEnum.ENABLE,
    sort: 0,
    remark: ''
  }
  formRef.value?.resetFields()
}
</script>

<template>
  <Dialog v-model="visible" :title="title" width="600px">
    <el-form ref="formRef" v-loading="formLoading && systemConfig.loadingType === 'module'" :model="formData" :rules="formRules" label-width="80px">
      <ElFormItem :label="t('sys.dict', 'title')" prop="dict_type">
        <el-select v-model="formData.dict_type" :placeholder="t('sys.dict.rules', 'title')" clearable filterable :disabled="formData.id !== undefined">
          <el-option v-for="item in dictTypeList" :key="item.type" :label="item.name" :value="item.type" />
        </el-select>
      </ElFormItem>
      <el-form-item :label="t('sys.dict', 'label')" prop="label">
        <el-input v-model="formData.label" clearable :placeholder="t('sys.dict.rules', 'label')" />
      </el-form-item>
      <el-form-item :label="t('sys.dict', 'value')" prop="value">
        <el-input v-model="formData.value" clearable :placeholder="t('sys.dict.rules', 'value')" />
      </el-form-item>
      <el-form-item :label="t('common', 'status')" prop="status">
        <el-radio-group v-model="formData.status" class="radio-button">
          <el-radio-button v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)" :key="dict.value" :value="dict.value">
            {{ dict.label }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="t('sys.dict', 'colorType')" prop="colorType">
        <el-select v-model="formData.color_type" clearable>
          <el-option v-for="item in colorTypeOptions" :key="item.value" :label="item.label + '(' + item.value + ')'" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('sys.dict', 'cssClass')" prop="cssClass">
        <el-input v-model="formData.css_class" clearable :placeholder="t('sys.dict.rules', 'cssClass')" />
      </el-form-item>
      <ElFormItem :label="t('common', 'sort')">
        <el-input-number v-model="formData.sort" />
      </ElFormItem>
      <el-form-item :label="t('common', 'remark')" prop="remark">
        <el-input v-model="formData.remark" clearable :placeholder="t('common.rules', 'remark')" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">{{ t('action', 'cancel') }}</el-button>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">{{ t('action', 'confirm') }}</el-button>
    </template>
  </Dialog>
</template>

<style scoped lang="scss">
.el-form{
  margin-right: -6px;
}
</style>
